package com.ktgj.customer.service.impl;

import java.io.File;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.ktgj.common.core.annotation.Excel;
import com.ktgj.common.core.constant.CustomerConstants;
import com.ktgj.common.core.constant.FileConstants;
import com.ktgj.common.core.domain.R;
import com.ktgj.common.core.enums.EmHelper;
import com.ktgj.common.core.exception.LoginException;
import com.ktgj.common.core.text.UUID;
import com.ktgj.common.core.utils.DateUtils;
import com.ktgj.common.core.utils.IDCardUtil;
import com.ktgj.common.core.utils.helper.StringHelper;
import com.ktgj.common.redis.service.RedisService;
import com.ktgj.customer.domain.*;
import com.ktgj.customer.domain.dto.*;
import com.ktgj.customer.domain.vo.*;
import com.ktgj.customer.mapper.*;
import com.ktgj.customer.service.IDepositBusinessService;
import com.ktgj.customer.service.IPointRecordService;
import com.ktgj.file.api.RemoteFilesService;
import com.ktgj.file.api.domain.SysFileApi;
import com.ktgj.flight.api.RemoteFlightService;
import com.ktgj.flight.api.domain.FlightOrderDTOCRM;
import com.ktgj.flight.api.domain.FlightOrderListVO;
import com.ktgj.flight.api.domain.TicketOrderApi;
import com.ktgj.hotel.api.RemoteHotelService;
import com.ktgj.hotel.api.domain.HotelOrderApi;
import com.ktgj.hotel.api.domain.HotelOrderPaginationVo;
import com.ktgj.hotel.api.domain.HotelParameterVo;
import com.ktgj.pay.api.RemotePayService;
import com.ktgj.pay.api.domain.InvoiceInvoiceOrderApi;
import com.ktgj.service.api.RemoteService;
import com.ktgj.service.api.domain.*;
import com.ktgj.system.api.domain.SysFile;
import com.ktgj.train.api.RemoteTrainService;
import com.ktgj.train.api.domain.TrainCRMOrder;
import com.ktgj.train.api.domain.TrainOrderApi;
import com.ktgj.train.api.domain.TrainOrderCRM;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.expression.CachedExpressionEvaluator;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Service;
import com.ktgj.customer.service.ICustomerService;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

/**
 * 会员基本信息Service业务层处理
 *
 * @author ruoyi
 * @date 2021-07-30
 */
@Service
public class CustomerServiceImpl implements ICustomerService {
    @Autowired
    private ContactlnformationMapper contactlnformationMapper;
    @Autowired
    private  CommonTravelersMapper commonTravelersMapper;
    @Autowired
    private  CommonReimbursementsMapper commonReimbursementsMapper;
    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private CustomerRightdetailMapper customerRightdetailMapper;
    @Autowired
    private CommonAddressesMapper commonAddressesMapper;
    @Autowired
    private CustomerCardMapper customerCardMapper;
    @Autowired
    private PointRecordMapper pointRecordMapper;
    @Autowired
    private BankCardMapper bankCardMapper;
    @Autowired
    private CardMapper cardMapper;
    @Autowired
    private RedisService redisService;
    @Autowired
    private RemoteService remoteService;
    @Autowired
    private RemoteTrainService remoteTrainService;
    @Autowired
    private RemoteHotelService remoteHotelService;
    @Autowired
    private RemoteFlightService remoteFlightService;
    @Autowired
    private IPointRecordService recordService;
    @Autowired
    private IDepositBusinessService depositBusinessService;
    @Autowired
    private EmployeeVipresourceMapper employeeVipresourceMapper;
    @Autowired
    private RemotePayService remotePayService;
    @Autowired
    private DepositBusinessMapper depositBusinessMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private DepartmentMapper departmentMapper;
    @Autowired
    private CustomerCardRecordMapper customerCardRecordMapper;
    @Autowired
    private InsuranceRecordMapper insuranceRecordMapper;
    @Autowired
    private CaseComplaintMapper caseComplaintMapper;
    @Autowired
    private BusinessOrderMapper businessOrderMapper;
    @Autowired
    private InsuranceCompanyMapper insuranceCompanyMapper;
    @Autowired
    private ICustomerService customerService;

    /**
     * 查询会员基本信息
     *
     * @param customerId 会员基本信息ID
     * @return 会员基本信息
     */
    @Override
    public Customer selectCustomerById(Long customerId)
    {
        Customer customer = customerMapper.selectCustomerById(customerId);
        List<CommonAddresses> commonAddressesList = commonAddressesMapper.selectCommonaddress(customerId);
        if (CollectionUtil.isNotEmpty(commonAddressesList))
        {
            customer.setCommonAddresses(new ArrayList<>());
            customer.setCommonAddresses(commonAddressesList);
        }
        List<CustomerRightdetail> lstCustomerRights = customerRightdetailMapper.selectCustomerRightdetailByCustomerId(customerId);
        if (CollectionUtil.isNotEmpty(lstCustomerRights))
        {
            customer.setLstCustomerRight(new ArrayList<>());
            customer.getLstCustomerRight().addAll(lstCustomerRights);
        }
        return customer;
    }


    /**
     * 根据会员ID获取会员权益中的券
     *
     * @param customerId
     * @return
     */
    @Override
    public List<CustomerRightdetail> getCustomerRightCoupon(Long customerId) {
        List<CustomerRightdetail> lstCustomerRights = customerRightdetailMapper.selectCustomerRightdetailByCustomerId(customerId);
        return lstCustomerRights.stream().filter(item -> item.getRightdetailType().equals(CustomerConstants.rightTypeCoupon.getValue())).collect(Collectors.toList());
    }

    /**
     * 查询会员基本信息列表
     *
     * @param customer 会员基本信息
     * @return 会员基本信息
     */
    @Override
    public List<Customer> selectCustomerList(Customer customer) {
        return customerMapper.selectCustomerList(customer);
    }

    @Override
    public List<CustomerReturnCard> selectCustomerReturnCardByPhone(String phone)  {
        List<CustomerReturnCard>list = customerMapper.selectCustomerReturnCardByPhone(phone);
        return list;
    }

    @Override
    public List<CustomerReturnCard> tmpSelectCustomerReturnCardByPhone(String phone) {
        List<CustomerReturnCard>list=customerMapper.tmpSelectCustomerReturnCardByPhone(phone);
        return list;
    }

    @Override
    public CustomerReturnCard selectCustomerReturnCardBycardCode(String cardCode) {
        return customerMapper.selectCustomerReturnCardBycardCode(cardCode);
    }

    /**
     * 新增会员基本信息
     *
     * @param customer 会员基本信息
     * @return 结果
     */
    @Override
    public int insertCustomer(Customer customer) {
        customer.setCreateTime(DateUtils.getNowDate());
        return customerMapper.insertCustomer(customer);
    }

    /**
     * 修改会员基本信息
     *
     * @param customer 会员基本信息
     * @return 结果
     */
    @Override
    public CustomerDto updateCustomerByCustomer(Customer customer, String token) {
        customerMapper.updateCustomer(customer);
        Object cacheObject = redisService.getCacheObject(token);
        if (cacheObject != null && cacheObject != "[]" && cacheObject.equals("[]")) {
            redisService.deleteObject(token);
        }

        Customer customerById = customerMapper.selectCustomerById(customer.getCustomerId());

        redisService.setCacheObject(token, JSON.toJSONString(customerById));

        customerMapper.updateCustomer(customer);

        CustomerDto customerDto = new CustomerDto();
        customerDto.setCustomerId(customer.getCustomerId());
        customerDto.setAvatar(customer.getAvatar());
        customerDto.setCustomerName(customer.getCustomerName());
        customerDto.setCustomerSex(customer.getCustomerSex());
        customerDto.setBirthday(customer.getBirthday());
        customerDto.setContractPhoneOne(customer.getContractPhoneOne());
        customerDto.setIdType(customer.getIdType());
        customerDto.setCustCertificateNo(customer.getCustCertificateNo());
        customerDto.setNickName(customer.getNickName());
        return customerDto;
    }

    /**
     * 修改会员基本信息
     *
     * @param customer 会员基本信息
     * @return 结果
     */
    @Override
    public Customer updateCustomer(Customer customer, String token) {
        int i = customerMapper.updateCustomer(customer);
        if (i > 0) {
            Object cacheObject = redisService.getCacheObject(token);
            if (cacheObject != null && cacheObject != "[]" && cacheObject.equals("[]")) {
                redisService.deleteObject(token);
            }

            Customer customerById = customerMapper.selectCustomerById(customer.getCustomerId());
            customerById.setToken(token);

            Collection<String> oneKeys = redisService.keys("*" + token);
            oneKeys.forEach(item -> redisService.setCacheObject(item, JSON.toJSONString(customerById)));

            return customerById;
        }
        return null;
    }

    @Override
    public int update(Customer customer) {
        return customerMapper.updateCustomer(customer);
    }

    /**
     * 查询当前会员信息
     */
    @Override
    public MemberInformationVo selectMemberInformation(Long customerId) {
        Customer customer = customerMapper.selectCustomerByCustomerId(customerId);
        MemberInformationVo memberInformationVo = new MemberInformationVo();
        memberInformationVo.setCustomerId(customerId);
        if(!customer.getCustomerSex().trim().equals("") && customer.getCustomerSex()!=null){
        if (customer.getCustomerSex().equals("male")) {
            customer.setCustomerSex("男");
        } else if (customer.getCustomerSex().equals("female")) {
            customer.setCustomerSex("女");
        }
        }
        BeanUtils.copyProperties(customer, memberInformationVo);
        memberInformationVo.setCertificateVoList(showCertificate());
        return memberInformationVo;
    }

    /**
     * 批量删除会员基本信息
     *
     * @param customerIds 需要删除的会员基本信息ID
     * @return 结果
     */
    @Override
    public int deleteCustomerByIds(Long[] customerIds) {
        return customerMapper.deleteCustomerByIds(customerIds);
    }

    /**
     * 删除会员基本信息信息
     *
     * @param customerId 会员基本信息ID
     * @return 结果
     */
    @Override
    public int deleteCustomerById(Long customerId) {
        return customerMapper.deleteCustomerById(customerId);
    }

    /**
     * 会员基本信息与常用地址对象关联查询（一对多）
     *
     * @param customerId
     * @return
     */
    @Override
    public List<Customer> selectCustomerAndCommonAddressesList(Long customerId) {
        return customerMapper.selectCustomerAndCommonAddressesList(customerId);
    }

    /**
     * 会员基本信息与常用报销凭证信息对象关联查询（一对多）
     *
     * @param customerId
     * @return
     */
    @Override
    public List<Customer> selectCustomerAndCommonReimbursementsList(Long customerId) {
        return customerMapper.selectCustomerAndCommonReimbursementsList(customerId);
    }

    /**
     * 会员基本信息与常用旅客信息对象关联查询（一对多）
     *
     * @param customerId
     * @return
     */
    @Override
    public List<Customer> selectCustomerAndCommonTravelersList(Long customerId) {
        return customerMapper.selectCustomerAndCommonTravelersList(customerId);
    }

    /**
     * 会员基本信息与银行卡信息对象关联查询（一对多）
     *
     * @param customerId
     * @return
     */
    @Override
    public List<Customer> selectCustomerAndBankCardList(Long customerId) {
        return customerMapper.selectCustomerAndBankCardList(customerId);
    }

    /**
     * 我的-编辑个人信息
     *
     * @param customer
     * @return
     */
    @Override
    public Customer updateCustomerLogin(Customer customer) {
        return customerMapper.updateCustomerLogin(customer);
    }

    /**
     * 我的-添加证件
     *
     * @param
     * @return
     */
    @Override
    public int updateCustomerByCertificate(Long customerId, String idType, String custCertificateNo, String invalidDate) {
        //截取字符串”2021-10-10----2021-11-11“-》”2021-11-11“
        invalidDate = invalidDate.substring(14, invalidDate.length());
        Customer customer = new Customer();
        customer.setCustomerId(customerId);
        customer.setIdType(idType);
        customer.setCustCertificateNo(custCertificateNo);
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            customer.setInvalidDate(sdf.parse(invalidDate));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return customerMapper.updateCustomerByCertificate(customer);
    }

    /**
     * 我的-积分
     *
     * @return
     */
    @Override
    public IntegralVo selectPointRecordByCustomerId(Long customerId) {
        List<PointRecord> pointRecordList = pointRecordMapper.selectPointRecordByCustomerId(customerId);
        IntegralVo integralVo = new IntegralVo();

        //当前用户可用积分
        Long integal = 0l;
        for (PointRecord pointRecord : pointRecordList) {
            //判断积分是否已过期
            Date date = new Date();
            int compareTo = pointRecord.getExpiredTime().compareTo(date);
            if (compareTo == 1 || pointRecord.getPntValue() <= 0) {//积分过期时间大于当前时间或积分为负数的积分相加
                integal += pointRecord.getPntValue();
            }
        }

        //更新可用积分
        if (pointRecordList.get(0).getAvailableValue() != integal) {
            PointRecord pointRecord = new PointRecord();
            pointRecord.setCustomerId(customerId);
            pointRecord.setAvailableValue(integal);
            pointRecordMapper.updatePointRecordByCustomerId(pointRecord);
        }

        //当前用户已使用积分
        Long used = 0l;
        for (PointRecord pointRecord : pointRecordList) {
            if (pointRecord.getPntValue() < 0) {//积分为负数的相加，used最后为负数
                used += pointRecord.getPntValue();
            }
        }

        //积分到期提示
        Long maturity = 0l;
        for (PointRecord pointRecord : pointRecordList) {
            if (pointRecord.getPntValue() > 0) {//积分大于0
                Date date = new Date();
                int days = (int) ((date.getTime() - pointRecord.getExpiredTime().getTime()) / (1000 * 3600 * 24));
                if (days <= 30 && days > 0) {//有效期小于等于30天且大于0的积分给予提示
                    maturity += pointRecord.getPntValue();
                }
            }
        }

        integralVo.setPointsAvailable(integal);
        //将当前用户已使用积分used截取为正数
        integralVo.setUsedPointsAvailable(Long.valueOf(used.toString().substring(1, used.toString().length())));
        integralVo.setExpiryReminder(maturity + "积分即将过期");
        return integralVo;
    }

    /**
     * 我的-信息
     */
    @Override
    public CurrentMemberVo selectCustomerByCustomerId(Long customerId) {
        CurrentMemberVo currentMemberVo = new CurrentMemberVo();
        Customer customer = customerMapper.selectCustomerById(customerId);
        List<PointRecord> pointRecordList = pointRecordMapper.selectPointRecordByCustomerId(customerId);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        //当前用户可用积分
        Long integal = 0l;
        for (PointRecord pointRecord : pointRecordList) {
            //判断积分是否已过期
            Date date = new Date();
            int compareTo = pointRecord.getExpiredTime().compareTo(date);
            if (compareTo == 1) {//积分过期时间大于当前时间
                integal += pointRecord.getPntValue();
            }
            if (pointRecord.getPntDirection() == 2) {//积分为支付
                integal -= pointRecord.getPntValue();
            }
        }

        int banCardNumber = bankCardMapper.banCardNumber(customerId);

        //当前用户的优惠券数量
        Long couponNum = customerRightdetailMapper.selectCustomerRightdetailCount(customerId);

        currentMemberVo.setAvatar(customer.getAvatar());
        currentMemberVo.setNickName(customer.getNickName());
        if (customer.getDepositSkipPwdAmount() != null && !customer.getDepositSkipPwdAmount().equals("")) {
            currentMemberVo.setGold(customer.getDepositSkipPwdAmount());
        } else {
            currentMemberVo.setGold(0l);
        }
        if (integal != null && !integal.equals("")) {
            currentMemberVo.setIntegral(integal);
        } else {
            currentMemberVo.setIntegral(0l);
        }

        currentMemberVo.setCouponNum(couponNum);
        currentMemberVo.setBankCardNum(Long.valueOf(banCardNumber));
        List<CustomerCard> customerCardList = customerCardMapper.CustomerCardList(customerId);
        List<Card> cardList = new ArrayList<>();
        for (CustomerCard customerCard : customerCardList) {
            Card card = cardMapper.selectCardByCardId(customerCard.getCardId());
            cardList.add(card);
        }

        Card card = card(cardList);
        currentMemberVo.setCustomerName(card.getCardSectionName());
        currentMemberVo.setCustomerNum(card.getCardId());
        currentMemberVo.setCustomerConnect(card.getBackgroundImageurl());
        for (CustomerCard customerCard : customerCardList) {
            if (customerCard.getCardId() == card.getCardId()) {
                currentMemberVo.setCustomerTime(format.format(customerCard.getInvalidDate()));
            }
        }
        return currentMemberVo;
    }

    /**
     * 证件类型显示
     */
    @Override
    public List<CertificateVo> showCertificate() {
        List<CertificateVo> certificateVoList = new CopyOnWriteArrayList<>();

        CertificateVo idCard = new CertificateVo();
        idCard.setCertificateName("身份证");
        idCard.setCertificateType("ID_CARD");

        CertificateVo militaryId = new CertificateVo();
        militaryId.setCertificateName("军人证");
        militaryId.setCertificateType("MILITARY_ID");

        CertificateVo passport = new CertificateVo();
        passport.setCertificateName("护照");
        passport.setCertificateType("PASSPORT");

        CertificateVo MTPFHKAMR = new CertificateVo();
        MTPFHKAMR.setCertificateName("港澳居民来往内地通行证");
        MTPFHKAMR.setCertificateType("MTPFHKAMR");

        CertificateVo MTPFTR = new CertificateVo();
        MTPFTR.setCertificateName("台湾居民来往大陆通行证");
        MTPFTR.setCertificateType("MTPFTR");

        CertificateVo RPFHKMATR = new CertificateVo();
        RPFHKMATR.setCertificateName("港澳台居民居住证");
        RPFHKMATR.setCertificateType("RPFHKMATR");

        CertificateVo PRICFF = new CertificateVo();
        PRICFF.setCertificateName("外国人永久居留身份证");
        PRICFF.setCertificateType("PRICFF");

        CertificateVo HKAMP = new CertificateVo();
        HKAMP.setCertificateName("港澳通行证");
        HKAMP.setCertificateType("HKAMP");

        CertificateVo accountBook = new CertificateVo();
        accountBook.setCertificateName("户口本");
        accountBook.setCertificateType("ACCOUNT_BOOK");

        CertificateVo birthCertificate = new CertificateVo();
        birthCertificate.setCertificateName("出生证明");
        birthCertificate.setCertificateType("BIRTH_CERTIFICATE");

        CertificateVo taiwanPass = new CertificateVo();
        taiwanPass.setCertificateName("台湾通行证");
        taiwanPass.setCertificateType("TAIWAN_PASS");

        certificateVoList.add(idCard);
        certificateVoList.add(militaryId);
        certificateVoList.add(passport);
        certificateVoList.add(MTPFHKAMR);
        certificateVoList.add(MTPFTR);
        certificateVoList.add(RPFHKMATR);
        certificateVoList.add(PRICFF);
        certificateVoList.add(HKAMP);
        certificateVoList.add(accountBook);
        certificateVoList.add(birthCertificate);
        certificateVoList.add(taiwanPass);
        return certificateVoList;
    }


    /**
     * 我的-积分明细
     */
    public PointRecordIntegraVo selectCustomerDetail(Long customerId, Date date) {
        List<PointRecord> pointRecordList = pointRecordMapper.selectPointRecordByCustomerId(customerId);//查询会员所有积分信息
        PointRecordIntegraVo pointRecordIntegraVo = new PointRecordIntegraVo();//返回对象
        List<PointRecordIntegraJustVo> pointRecordIntegraJustVoList = new CopyOnWriteArrayList<>();//获取积分集合
        List<PointRecordIntegraBurdenVo> pointRecordIntegraBurdenVoList = new CopyOnWriteArrayList<>();//支出积分集合

        Long totalPoints = 0l;//总积分
        Long earnPoints = 0l;//获取
        Long spendingPoints = 0l;//支出

        SimpleDateFormat yearFormat = new SimpleDateFormat("yyyy");
        SimpleDateFormat monthFormat = new SimpleDateFormat("MM");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");

        String yearDate = yearFormat.format(date);
        String monthDate = monthFormat.format(date);

        //获取指定年月的积分流动记录
        for (PointRecord pointRecord : pointRecordList) {
            String year = yearFormat.format(pointRecord.getOperationTime());
            String month = monthFormat.format(pointRecord.getOperationTime());

            if (year.equals(yearDate) && month.equals(monthDate)) {//将年和月与参数对比，结果为true时证明该数据符合条件
                if (pointRecord.getPntDirection() == 1) {//获取积分
                    PointRecordIntegraJustVo pointRecordIntegraJustVo = new PointRecordIntegraJustVo();//获取去积分对象
                    earnPoints = earnPoints + pointRecord.getPntValue();
                    pointRecordIntegraJustVo.setObtainPntValue(pointRecord.getPntValue());
                    pointRecordIntegraJustVo.setObtainOperationTime(format.format(pointRecord.getOperationTime()));
                    pointRecordIntegraJustVo.setObtainPntReasonDesc(pointRecord.getPntReasonDesc());
                    pointRecordIntegraJustVoList.add(pointRecordIntegraJustVo);
                } else if (pointRecord.getPntDirection() == 2) {//支出积分
                    PointRecordIntegraBurdenVo pointRecordIntegraBurdenVo = new PointRecordIntegraBurdenVo();//支出积分对象
                    spendingPoints = spendingPoints + pointRecord.getPntValue();
                    pointRecordIntegraBurdenVo.setExpenditurePntValue(pointRecord.getPntValue());
                    pointRecordIntegraBurdenVo.setExpenditureOperationTime(format.format(pointRecord.getOperationTime()));
                    pointRecordIntegraBurdenVo.setExpenditurePntReasonDesc(pointRecord.getPntReasonDesc());
                    pointRecordIntegraBurdenVoList.add(pointRecordIntegraBurdenVo);
                }
            }
        }
        totalPoints = earnPoints - spendingPoints;
        pointRecordIntegraVo.setTotalPoints(totalPoints);
        pointRecordIntegraVo.setSpendingPoints(spendingPoints);
        pointRecordIntegraVo.setQueryDate(date);
        pointRecordIntegraVo.setEarnPoints(earnPoints);
        pointRecordIntegraVo.setPointRecordIntegraBurdenVoList(pointRecordIntegraBurdenVoList);
        pointRecordIntegraVo.setPointRecordIntegraJustVoList(pointRecordIntegraJustVoList);
        return pointRecordIntegraVo;
    }

    /**
     * 修改密码
     */
    @Override
    public int updateCustomerByCustLoginPswmd5(Long customerId, String NewCustLoginPswmd5One,
                                               String NewCustLoginPswmd5Two, String CustLoginPswmd5) {
        String md5One = DigestUtils.md5Hex(NewCustLoginPswmd5One);
        String md5Two = DigestUtils.md5Hex(NewCustLoginPswmd5Two);
        String oldMd5 = DigestUtils.md5Hex(CustLoginPswmd5);

        char[] special = NewCustLoginPswmd5One.toCharArray();

        boolean flag = true;

        for (int i = 0; i <= special.length; i++) {//
            if ((special[i] == 95) || (special[i] == 46) || (special[i] > 48 && special[i] < 57) ||
                    (special[i] > 97 && special[i] < 122) || (special[i] > 65 && special[i] < 90)) {
                flag = false;
            } else {
                flag = true;
                break;
            }
        }

        Customer customer = customerMapper.selectCustomerByCustomerIdMd5(customerId);

        int numMd5One = NewCustLoginPswmd5One.indexOf(" ");

        //判断当前密码是否正确
        if (!oldMd5.equals(customer.getCustLoginPswmd5())) {
            throw new LoginException("密码输入错误！");
        } else if (customer.getCustLoginPswmd5().equals(md5One)) {//判断新密码与原密码是否相同
            throw new LoginException("新密码不能与原密码相同！");
        } else if (!md5One.equals(md5Two)) {//判断两次新密码是否一致
            throw new LoginException("新密码两次输入不一致！");
        } else if (NewCustLoginPswmd5One.length() < 8 || NewCustLoginPswmd5One.length() > 20) {
            throw new LoginException("新密码需为8-20位，数字、英文和\"_\",\".\"的组合！");
        } else if (numMd5One != -1) {
            throw new LoginException("新密码不能包含空格");
        } else if (flag) {
            throw new LoginException("新密码不能包含非法字符");
        } else {
            Customer cto = new Customer();
            cto.setCustomerId(customerId);
            cto.setCustLoginPswmd5(md5Two);
            return customerMapper.updateCustomerByCustLoginPswmd5(cto);
        }
    }

    /**
     * 积分到期提示列表
     */
    @Override
    public List<WillExpireSoonVo> willExpireSoonIntegral(Long customerId) {
        List<PointRecord> pointRecordList = pointRecordMapper.selectPointRecordIntegral(customerId);
        List<WillExpireSoonVo> willExpireSoonVoList = new ArrayList<>();
        Date time = new Date();
        if (pointRecordList.size() > 0) {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            for (PointRecord pointRecord : pointRecordList) {
                if (pointRecord.getPntDirection() == 1) {
                    String date = format.format(pointRecord.getExpiredTime());
                    String dateTime = format.format(time);
                    boolean boo = dayTime(date);
                    if (date.compareTo(dateTime) >= 0 && boo) {
                        WillExpireSoonVo willExpireSoonVo = new WillExpireSoonVo();
                        willExpireSoonVo.setExpireDate(date);
                        willExpireSoonVo.setWillExpireSoonNum(pointRecord.getPntValue().toString());
                        willExpireSoonVoList.add(willExpireSoonVo);
                    }
                }
            }
        } else {
            return null;
        }
        return willExpireSoonVoList;
    }

    @Override
    public Customer getCustomerByMobileId(String mobileId) {
        Customer customer = customerMapper.selectCustomerByContractPhoneOnes(mobileId);
        if (customer == null) {
            return null;
        }
        return customer;
    }

    @Override
    public String getCustomerCardDisplay(Long customerId) {
        return customerMapper.getCustomerCardDisplay(customerId);
    }

    @Override
    public long getCustomerCardExpireDays(Long customerId) {
        Date date = customerMapper.getCustomerCardExpireDays(customerId);
        Date now = new Date();
        long diff = date.getTime() - now.getTime();
        long diffDays = diff / (24 * 60 * 60 * 1000);
        return diffDays;
    }

    /**
     * 登机牌会员价格汇总
     */
    @Override
    public List<SummaryVo> customerPriceSummary(Long customerId) {
        Map<String, Object> map = new HashMap<>();
        map.put("customerId", customerId);
        List<SummaryVo> summaryVoList = new ArrayList<>();

        //代理登机牌
        BoardingPassVoApi boardingPassVo = remoteService.orderBoardingNum(map);
        SummaryVo vipBoarding = new SummaryVo();
        vipBoarding.setBusinessLineName("代理登机牌");
        vipBoarding.setOrderNum(boardingPassVo.getUsageCountNum());
        summaryVoList.add(vipBoarding);

        //贵宾厅
        List<OrderViphallVoApi> orderViphalls = remoteService.orderViphallByCustomer(map);
        SummaryVo vipHall = new SummaryVo();
        vipHall.setBusinessLineName("贵宾厅");
        vipHall.setOrderNum(orderViphalls.size());
        summaryVoList.add(vipHall);

        //火车票
        List<TrainOrderApi> trainOrderApis = remoteTrainService.trainOrderNum(map);
        SummaryVo train = new SummaryVo();
        train.setBusinessLineName("火车票");
        train.setOrderNum(trainOrderApis.size());
        summaryVoList.add(train);

        //酒店
        List<HotelOrderApi> hotelOrders = remoteHotelService.hotelOrderNum(map);
        SummaryVo hotel = new SummaryVo();
        hotel.setBusinessLineName("酒店");
        hotel.setOrderNum(hotelOrders.size());
        summaryVoList.add(hotel);

        //机票
        List<TicketOrderApi> ticketOrderApis = remoteFlightService.checkTheTicketList(customerId);
        SummaryVo ticket = new SummaryVo();
        ticket.setBusinessLineName("酒店");
        ticket.setOrderNum(ticketOrderApis.size());
        summaryVoList.add(ticket);

        return summaryVoList;
    }

    @Override
    public Customer selectCustomerPhoneById(Long customerId) {
        return customerMapper.selectCustomerPhoneById(customerId);
    }

    @Override
    public Customer customerPhoneLogin(String phone) {
        return customerMapper.customerPhoneLogin(phone);
    }

    //查询会员信息
    @Override
    public CustomerCRM queryCustomer(String phone, String idCode, String cardNum) throws Exception {
        CustomerCRM customer = new CustomerCRM();

        Long id = null;
        if (cardNum != null && !cardNum.equals("") && !cardNum.equals("null")){
            CustomerIdVo customerIdVo = new CustomerIdVo();
            customerIdVo.setCustomerCard(cardNum);
            try {
                customerIdVo = customerService.customerId(customerIdVo);
            } catch (Exception e){
                throw new Exception(e.getMessage());
            }

            if (customerIdVo != null){
                id = customerIdVo.getCustomerId();
            }
        }

        Customer queryCustomer = customerMapper.queryCustomer(phone, idCode, id);
        if (queryCustomer==null) {
            return null;
        }
        BeanUtils.copyProperties(queryCustomer, customer);
        List<CustomerCardDTO> lstCard = customerCardMapper.selectCustomerCardByCustomerId(queryCustomer.getCustomerId());
        customer.getLstCustomerCard().addAll(lstCard);
        BigDecimal bigDecimal = depositBusinessService.queyUserDepositBusiness(queryCustomer.getCustomerId());
        if (bigDecimal != null && bigDecimal.compareTo(new BigDecimal(0)) != 0){
            customer.setGold(bigDecimal.longValue());
        }
        else {
            customer.setGold(0l);
        }
        return customer;
    }
    //查询会员信息根据手机号
    public  Customer selectCustomerByPhone(String phone,String idCode){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Customer customer = customerMapper.queryCustomer(phone, idCode, 0l);
        if(customer !=null) {
            customer.getCommonAddresses().addAll(commonAddressesMapper.selectCommonaddress(customer.getCustomerId()));
            customer.getCommonReimbursements().addAll(commonReimbursementsMapper.selectCommonReimbursements(customer.getCustomerId()));
            List<BankCard> bankCards = bankCardMapper.selectBankCardByMemberId(customer.getCustomerId());
            if (bankCards != null && bankCards.size() > 0) {
                bankCards.forEach(item -> {
                    if (item.getBankName() != null && !item.getBankName().equals("") && item.getCardNumber() != null && !item.getCardNumber().equals(""))
                        item.setBankName(item.getBankName() + item.getCardNumber().substring(item.getCardNumber().length() - 4));
                });
                customer.getBankCard().addAll(bankCards);
            }
            List<CommonTravelers> commonTravelers = commonTravelersMapper.selectCommonTravelersByMemberId(customer.getCustomerId());
            for (CommonTravelers cc:commonTravelers)
            {
                cc.setTrvelersId(cc.getCommonTrvelersId().toString());
            }
            customer.getCommonTravelers().addAll(commonTravelers);
            customer.getContactInformations().addAll(contactlnformationMapper.backContactInformationById(customer.getCustomerId()));
            List<InvoiceInvoiceOrderApi> lstInvoice =  remotePayService.getListByCustomerId(customer.getCustomerId().toString());
            if (CollectionUtil.isNotEmpty(lstInvoice))
            {
                customer.getInvoiceInvoiceOrderApis().addAll(lstInvoice);
            }
            List<InsuranceRecord> insuranceRecordList = insuranceRecordMapper.insuranceRecordList(customer.getCustomerId());
            if (insuranceRecordList != null && insuranceRecordList.size() > 0)
            {
                for (InsuranceRecord insuranceRecord : insuranceRecordList)
                {
                    if (insuranceRecord.getInsCoId() != null)
                    {
                        InsuranceCompany insuranceCompany = insuranceCompanyMapper.insuranceCompany(insuranceRecord.getInsCoId());
                        if (insuranceCompany != null)
                        {
                            insuranceRecord.setInsCoName(insuranceCompany.getInsCoName());
                        }
                    }
                }
            }
            customer.setInsuranceRecordList(insuranceRecordList);

            List<CaseComplaint> caseComplaints = caseComplaintMapper.caseComplaintList(customer.getCustomerId());
            customer.setCaseComplaintList(caseComplaints);

            List<PurchaseCardVo> purchaseCardVoList = new ArrayList<>();
            List<PurchaseCardVo> purchaseCardVos = businessOrderMapper.orderList(customer.getCustomerId());
            if (purchaseCardVos.size() > 0){
                for (PurchaseCardVo purchaseCardVo : purchaseCardVos) {
                    purchaseCardVoList.add(purchaseCardVo);
                    /*if (purchaseCardVoList.size() == 3){
                        break;
                    }*/
                }
            }
            customer.setPurchaseCardVoList(purchaseCardVoList);


        }
        return customer;
    }

    //会员识别查询
    @Override
    public List<CustomerIdentify> selectCustomerIdentify(CustomerIdentify customerIdentify) {
        List<CustomerIdentify> identifyList = customerMapper.selectCustomerIdentify(customerIdentify);
        //
        List<CustomerIdentify> identify=new ArrayList<>();
        //查有几人
        for (CustomerIdentify c : identifyList) {
            Long totalPoints = 0l;//总积分
            Long earnPoints = 0l;//获取
            Long spendingPoints = 0l;//支出
            CustomerIdentify identifys = new CustomerIdentify();
            //每人有多少条积分数据
            List<CustomerIdentify> list = customerMapper.selectPointBy(c.getCustomerId());
            for (CustomerIdentify cc : list) {
                Date date = new Date();
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                if (date.before(cc.getExpiredTime())) {
                    if (cc.getPntDirection() == 1) {
                        earnPoints = earnPoints + cc.getPntvalue();
                    } else if (cc.getPntDirection() == 2) {
                        spendingPoints = spendingPoints + cc.getPntvalue();
                    }
                }
                totalPoints = earnPoints - spendingPoints;
                if (totalPoints < 0) {
                    totalPoints = 0l;
                    c.setAvailableValue(totalPoints);
                } else {
                    c.setAvailableValue(totalPoints);
                }
            }
            BeanUtils.copyProperties(c, identifys);

            identify.add(identifys);
        }
        return identify;
    }
    //查询一个会员有几张卡
    @Override
    public List<CustomerReturnCard> getCustomerCardByCustomerId(Long customerId) {
        List<CustomerReturnCard> customerReturnCardList = new ArrayList<>();
        List<CustomerCard> customerCards = customerCardMapper.CustomerCardList(customerId);
        if (customerCards != null && customerCards.size() > 0){
            for (CustomerCard customerCard : customerCards) {
                Card card = null;
                Employee employee = null;
                Employee list = null;
                Department department = null;
                if (customerCard != null && customerCard.getCardId() != null){
                    card = cardMapper.cardLevel(customerCard.getCardId());
                }
                if (customerCard != null && customerCard.getCarddmansId() != null){
                    employee = employeeMapper.employeeNameList(customerCard.getCarddmansId());
                }
                if (customerCard != null && customerCard.getActiveEmployeeId() != null){
                    list = employeeMapper.employeeNameList(customerCard.getCarddmansId());
                }
                if (employee != null && employee.getDeptId() != null){
                    department = departmentMapper.selectDepartmentById(employee.getDeptId());
                }

                CustomerReturnCard customerReturnCard = new CustomerReturnCard();
                customerReturnCard.setCustomerCardId(customerCard.getCustomerCardId());
                if (card != null){
                    customerReturnCard.setCardSettionname(card.getCardSectionName());
                }
                customerReturnCard.setCardCode(customerCard.getCardCode());
                customerReturnCard.setCustomerId(customerId);
                if (customerCard.getCardStatus().equals(CustomerConstants.valid.getValue())){
                    customerReturnCard.setCardStatus("已生效");
                }
                else if (customerCard.getCardStatus().equals(CustomerConstants.invalid.getValue())){
                    customerReturnCard.setCardStatus("已失效");
                }
                if (employee != null){
                    customerReturnCard.setEmployee(employee.getEmployeeName());
                }
                if (department != null){
                    customerReturnCard.setDepartmentName(department.getDeptName());
                }
                customerReturnCard.setCardSaleDate(customerCard.getValidDate());
                if (list != null){
                    customerReturnCard.setCardStartName(list.getEmployeeName());
                }
                customerReturnCardList.add(customerReturnCard);
            }
        }

        return customerReturnCardList;
    }

    /**
     * 会员信息查id
     */
    @Override
    public Long customerByCustomerName(VipCustomerVo vipCustomerVo) {
        Long customerId = null;
        Long vipCustomerId = null;
        //会员卡号
        if (vipCustomerVo.getCardCode() != null && !vipCustomerVo.getCardCode().equals("")) {
            customerId = customerCardMapper.customerId(vipCustomerVo.getCardCode()).getCustomerId();
        }
        //会员姓名
        if (vipCustomerVo.getCustomerName() != null && !vipCustomerVo.getCustomerName().equals("")) {
            vipCustomerId = customerMapper.customerByCustomerName(vipCustomerVo.getCustomerName()).getCustomerId();
        }

        if ((customerId != null && customerId != 0) && (vipCustomerId == null || vipCustomerId == 0)) {
            return customerId;
        } else if ((customerId == null || customerId == 0) && (vipCustomerId != null && vipCustomerId != 0)) {
            return vipCustomerId;
        } else if (customerId != null && customerId != 0 && vipCustomerId != null && vipCustomerId != 0) {
            if (customerId == vipCustomerId) {
                return customerId;
            } else {
                return null;
            }
        } else {
            return null;
        }
    }

    @Override
    public CustomerCRMDataDTO queryCRMCustomerData(Long customerId, String phone, String certificateNo, String cardCode, String customerName) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        CustomerCRMDataDTO customerCRMDataDTO = customerMapper.queryCustomerCondition(customerId, phone, certificateNo, cardCode, customerName);//会员id&会员姓名
        if (customerCRMDataDTO == null){
            customerCRMDataDTO = new CustomerCRMDataDTO();
            return customerCRMDataDTO;
        }
        //todo 用户频率
        customerCRMDataDTO.setCustomerCode(DigestUtils.md5Hex(customerCRMDataDTO.getCustomerId().toString()));

        /**
         * vip经理
         */
        CustomerCRMDataDTO employeeVipResource = employeeVipresourceMapper.queryVipresourceById(customerCRMDataDTO.getCustomerId());
        if (employeeVipResource != null) {
            customerCRMDataDTO.setDeptName(employeeVipResource.getDeptName());//部门名称
            customerCRMDataDTO.setEmployeeName(employeeVipResource.getEmployeeName());//vip经理姓名
            customerCRMDataDTO.setVIPStatus("分配");//todo 开启状态
            customerCRMDataDTO.setVIPTime(employeeVipResource.getVIPTime());//分配时间
        } else {
            customerCRMDataDTO.setVIPStatus("未分配");
        }

        List<CustomerCRMDataCardDataDTO> customerCRMDataCardDataDTOS = customerCardMapper.queryCustomerCRMDataCardDataDTO(customerCRMDataDTO.getCustomerId());// todo 购买时间、过期时间、待执行次数
        if (customerCRMDataCardDataDTOS != null && customerCRMDataCardDataDTOS.size() > 0){
            for (CustomerCRMDataCardDataDTO customerCRMDataCardDataDTO : customerCRMDataCardDataDTOS) {
                if (customerCRMDataCardDataDTO.getInvalidDTime() != null){
                    customerCRMDataCardDataDTO.setInvalidDate(format.format(customerCRMDataCardDataDTO.getInvalidDTime()));
                }
                if (customerCRMDataCardDataDTO.getPurchaseTime() != null){
                    customerCRMDataCardDataDTO.setPurchaseDate(format.format(customerCRMDataCardDataDTO.getPurchaseTime()));
                }
                CustomerCardRecord customerCardRecord = new CustomerCardRecord();
                customerCardRecord.setCustormerId(customerCRMDataDTO.getCustomerId());
                customerCardRecord.setCardId(customerCRMDataCardDataDTO.getCardId());
                List<CustomerCardRecord> lstCustomerRecord = customerCardRecordMapper.selectCustomerCardRecordList(customerCardRecord);
                if (lstCustomerRecord != null && lstCustomerRecord.size()>0)
                {
                    customerCRMDataCardDataDTO.setUnExecutedNum(lstCustomerRecord.size());
                    lstCustomerRecord = lstCustomerRecord.stream().sorted(Comparator.comparing(CustomerCardRecord::getExecutedate).reversed()).collect(Collectors.toList());
                    Date validDate = lstCustomerRecord.get(0).getExecutedate();
                    for (CustomerCRMDataCardDataDTO customerCard: customerCRMDataCardDataDTOS)
                    {
                        if (customerCard.getCardId().equals(customerCRMDataCardDataDTO.getCardId()))
                        {
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                            customerCard.setInvalidDate(sdf.format(validDate));
                        }
                    }
//                    customerCRMDataDTO.setInvalidDTime(lstCustomerRecord.get(0).getExecutedate());
                }
            }
        }

        customerCRMDataDTO.setCardDataList(customerCRMDataCardDataDTOS);

        List<RightCouponDTO> couponDTOS = customerRightdetailMapper.getCustomerTravelMoney(customerCRMDataDTO.getCustomerId());
        /** 会员资产 */
        customerCRMDataDTO.setPointNum(recordService.queryUserCreditsNum(customerCRMDataDTO.getCustomerId()));//积分数量
        BigDecimal travelMoney = new BigDecimal(0);//旅游抵扣券余额
        Long couponNum = new Long(0);//优惠券数量
        BigDecimal commodityMoney = new BigDecimal(0);//商品抵扣券余额
        Long flightDelayNum = new Long(0);//航班延误体验券数量
        Long flightDCancellationNum = new Long(0);//航班取消体验券数量
        Long VIPHallNum = new Long(0);//贵宾厅、餐厅体验券数量
        boolean isInfiniteVIPHall = false;
        /** 出行/健康产品 */
        Long admissionTicketNum = new Long(0);//景区门票数量
        Long DDDrivingNum = new Long(0);//滴滴代驾券数量
        Long testNum = new Long(0);//体检数量
        Long registerNum = new Long(0);//挂号数量
        boolean isInfiniteRegister = false;
        Long consultationNum = new Long(0);//在线问诊数量
        Long doctorNum = new Long(0);//私人医生数量

        if (couponDTOS != null && couponDTOS.size() > 0){
            for (RightCouponDTO item : couponDTOS) {
                if (item.getCouponType().equals(CustomerConstants.CouponTypeTravel.getValue()))
                    travelMoney = travelMoney.add(item.getCouponMoney());
                if (item.getCouponType().equals(CustomerConstants.CouponTypeFullMinus.getValue())
                        || item.getCouponType().equals(CustomerConstants.CouponTypeCashCoupon.getValue())
                        || item.getCouponType().equals(CustomerConstants.CouponTypeDiscount.getValue()))
                    couponNum = couponNum + 1;
                if (item.getCouponType().equals(CustomerConstants.CouponTypeCommodity.getValue()))
                    commodityMoney = commodityMoney.add(item.getCouponMoney());
                if (item.getCouponType().equals(CustomerConstants.CouponTypeFlightDelay.getValue()))
                    flightDelayNum = flightDelayNum + 1;
                if (item.getCouponType().equals(CustomerConstants.CouponTypeFlightDCancellation.getValue()))
                    flightDCancellationNum = flightDCancellationNum + 1;
                if (item.getCouponType().equals(CustomerConstants.CouponTypeVIPHall.getValue()) && !isInfiniteVIPHall)
                    VIPHallNum = VIPHallNum + 1;
                if (item.getCouponType().equals(CustomerConstants.CouponTypeInfiniteVIPHall.getValue())) {
                    isInfiniteVIPHall = true;
                    VIPHallNum = 9999L;
                }
                if (item.getCouponType().equals(CustomerConstants.CouponTypeAdmissionTicket.getValue()))
                    admissionTicketNum = admissionTicketNum + 1;
                if (item.getCouponType().equals(CustomerConstants.CouponTypeDD.getValue()))
                    DDDrivingNum = DDDrivingNum + 1;
                if (item.getCouponType().equals(CustomerConstants.CouponTypeTest.getValue()))
                    testNum = testNum + 1;
                if (item.getCouponType().equals(CustomerConstants.CouponTypeRegister.getValue()) && !isInfiniteRegister)
                    registerNum = registerNum + 1;
                if (item.getCouponType().equals(CustomerConstants.CouponTypeInfiniteRegister.getValue())) {
                    isInfiniteRegister = true;
                    registerNum = 9999L;
                }
                if (item.getCouponType().equals(CustomerConstants.CouponTypeInfiniteConsultation.getValue()))
                    consultationNum = 9999L;
                if (item.getCouponType().equals(CustomerConstants.CouponTypeDoctor.getValue()))
                    doctorNum = 9999L;
            }
        }

        customerCRMDataDTO.setTravelMoney(travelMoney);
        customerCRMDataDTO.setCouponNum(couponNum);
        customerCRMDataDTO.setCommodityMoney(commodityMoney);
        customerCRMDataDTO.setFlightDelayNum(flightDelayNum);
        customerCRMDataDTO.setFlightDCancellationNum(flightDCancellationNum);
        customerCRMDataDTO.setVIPHallNum(VIPHallNum);
        customerCRMDataDTO.setAdmissionTicketNum(admissionTicketNum);
        customerCRMDataDTO.setDDDrivingNum(DDDrivingNum);
        customerCRMDataDTO.setTestNum(testNum);
        customerCRMDataDTO.setRegisterNum(registerNum);
        customerCRMDataDTO.setConsultationNum(consultationNum);
        customerCRMDataDTO.setDoctorNum(doctorNum);

        /**
         * 零钱
         */
        List<DepositBusiness> lstDeposits = depositBusinessMapper.depositBusinessByCustomerId(customerCRMDataDTO.getCustomerId());
        List<DepositBusiness> lstInc =  lstDeposits.stream().filter(item->item.getState().equals("true") && item.getChangetype()==1).collect(Collectors.toList());
        List<DepositBusiness> lstDec =  lstDeposits.stream().filter(item->item.getState().equals("true") && item.getChangetype()==2).collect(Collectors.toList());
        BigDecimal incValue = getDepositValue(lstInc);
        BigDecimal decValue = getDepositValue(lstDec);
        customerCRMDataDTO.setDeposit(incValue.subtract(decValue));
//        BigDecimal bigDecimal = depositBusinessMapper.queryDepositBusiness(customerCRMDataDTO.getCustomerId());
//        if (bigDecimal != null && bigDecimal.compareTo(new BigDecimal(0)) != -1){
//            customerCRMDataDTO.setDeposit(bigDecimal);//金币总额
//        }
        List<DepositBusiness> lstTmpInc1 =  lstDeposits.stream().filter(item->item.getState().equals("true") && item.getDrawState().equals("true") && item.getChangetype()==1).collect(Collectors.toList());
        List<DepositBusiness> lstTmpDec1 =  lstDeposits.stream().filter(item->item.getState().equals("true") && item.getDrawState().equals("true") && item.getChangetype()==2).collect(Collectors.toList());
        BigDecimal incValue1 = getDepositValue(lstTmpInc1);
        BigDecimal decValue1 = getDepositValue(lstTmpDec1);
        customerCRMDataDTO.setExtractDeposit(incValue1.subtract(decValue1));


//        BigDecimal canCashMoney = lstDeposits.stream().filter(item->item.)
//        BigDecimal decimal = depositBusinessMapper.queryExtractDepositBusiness(customerCRMDataDTO.getCustomerId());
//        if (decimal != null && decimal.compareTo(new BigDecimal(0)) != -1){
//            customerCRMDataDTO.setExtractDeposit(decimal);//可提现金币
//        }

        List<DepositBusiness> lstTmpInc2 =  lstDeposits.stream().filter(item->item.getState().equals("true") && item.getDrawState().equals("false") && item.getChangetype()==1).collect(Collectors.toList());
        List<DepositBusiness> lstTmpDec2 =  lstDeposits.stream().filter(item->item.getState().equals("true") && item.getDrawState().equals("false") && item.getChangetype()==2).collect(Collectors.toList());
        BigDecimal incValue2 = getDepositValue(lstTmpInc2);
        BigDecimal decValue2 = getDepositValue(lstTmpDec2);
        customerCRMDataDTO.setNoExtractDeposit(incValue2.subtract(decValue2));
//        BigDecimal queryNoExtractDepositBusiness = depositBusinessMapper.queryNoExtractDepositBusiness(customerCRMDataDTO.getCustomerId());
//        if (queryNoExtractDepositBusiness != null && queryNoExtractDepositBusiness.compareTo(new BigDecimal(0)) != -1){
//            customerCRMDataDTO.setNoExtractDeposit(queryNoExtractDepositBusiness);//不可提现金币
//        }
        List<DepositBusiness> lstFrozenInc = lstDeposits.stream().filter(item->item.getState().equals("true") && item.getLockState().equals("true") && item.getChangetype()==1).collect(Collectors.toList());
        List<DepositBusiness> lstFrozenDec = lstDeposits.stream().filter(item->item.getState().equals("true") && item.getLockState().equals("true") && item.getChangetype()==2).collect(Collectors.toList());
        BigDecimal forzenIncValue = getDepositValue(lstFrozenInc);
        BigDecimal forzenDecValue = getDepositValue(lstFrozenDec);
        customerCRMDataDTO.setFrozenDeposit(forzenIncValue.subtract(forzenDecValue));

//        BigDecimal frozenDepositBusiness = depositBusinessMapper.queryFrozenDepositBusiness(customerCRMDataDTO.getCustomerId());
//        if (frozenDepositBusiness != null && frozenDepositBusiness.compareTo(new BigDecimal(0)) != -1)
//        {
//            customerCRMDataDTO.setFrozenDeposit(frozenDepositBusiness);//冻结金币
//        }

        /**
         * 会员权益使用
         */
        BigDecimal queryUseCommodityMoney = customerRightdetailMapper.queryUseCommodityMoney(customerCRMDataDTO.getCustomerId());
        if (queryUseCommodityMoney != null && queryUseCommodityMoney.compareTo(new BigDecimal(0)) != -1){
            customerCRMDataDTO.setUseCommodityMoney(queryUseCommodityMoney);//使用的商品抵扣券金额
        }

        VipchannelOrederParameterVo vipchannelOrederParameterVo = new VipchannelOrederParameterVo();
        vipchannelOrederParameterVo.setCustomerId(customerId);
        vipchannelOrederParameterVo.setPhone(phone);
        List<OrderViphall> orderViphalls = remoteService.VipchannelOrederList(vipchannelOrederParameterVo);
        if (orderViphalls != null){
            customerCRMDataDTO.setUseVIPHallNum(new Long(orderViphalls.size()));//使用贵宾厅次数
        }

        List<OrderVipchannel> orderVipchannels = remoteService.VipchannelOrederListVo(vipchannelOrederParameterVo);
        if (orderVipchannels != null){
            customerCRMDataDTO.setUseVIPChannelNum(new Long(orderVipchannels.size()));//使用vip通道次数
        }

        FlightOrderDTOCRM flightOrderDTOCRM = new FlightOrderDTOCRM();
        flightOrderDTOCRM.setGustPhone(phone);
        List<FlightOrderListVO> flightOrderListVOS = remoteFlightService.orderList(flightOrderDTOCRM);
        if (flightOrderListVOS != null){
            customerCRMDataDTO.setUseFlightNum(new Long(flightOrderListVOS.size()));//机票订单数
        }

        HotelParameterVo hotelParameterVo = new HotelParameterVo();
        hotelParameterVo.setPhone(phone);
        HotelOrderPaginationVo hotelOrderPaginationVo = remoteHotelService.orderList(hotelParameterVo);
        if (hotelOrderPaginationVo != null){
            customerCRMDataDTO.setUseHotelNum(new Long(hotelOrderPaginationVo.getTotalNumber()));//酒店订单数
        }

        TrainCRMOrder trainCRMOrder = new TrainCRMOrder();
        trainCRMOrder.setLinkPhone(phone);
        List<TrainOrderCRM> trainOrderCRMS = remoteTrainService.orderList(trainCRMOrder);
        if (trainOrderCRMS != null){
            customerCRMDataDTO.setUseTrainNum(new Long(trainOrderCRMS.size()));//火车票订单数
        }

        List<OrderBoarding> orderBoardings = remoteService.orederList(vipchannelOrederParameterVo);
        if (orderBoardings != null){
            customerCRMDataDTO.setUseVIPBoardingNum(new Long(orderBoardings.size()));//值机订单数量
        }

        return customerCRMDataDTO;
    }

    public BigDecimal getDepositValue(List<DepositBusiness> lstData)
    {
        BigDecimal value = new BigDecimal(0);
        for (DepositBusiness depositBusiness : lstData)
        {
            if (depositBusiness.getDetailamount() != null)
            {
                value = value.add(depositBusiness.getDetailamount());
            }
        }
        return value;
    }

    @Override
    public Customer InquireCustomerById(Long customerId) {
        return customerMapper.InquireCustomerById(customerId);
    }
    /**
     * 退卡审核2
     * @param customerReturnCard
     * @return
     */
    @Override
    public List<CustomerReturnCard> selectCustomerReturnCardByorderDate(CustomerReturnCard customerReturnCard) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (customerReturnCard.getCreateDate() != null){
            try {
                Date createDate = format.parse(format.format(customerReturnCard.getCreateDate()));
                customerReturnCard.setCreateDate(createDate);
            } catch (Exception e){
                throw new Exception("日期转换错误");
            }
        }
        if (customerReturnCard.getInvalidDate() != null){
            try {
                Date invalidDate = format.parse(format.format(customerReturnCard.getInvalidDate()));
                customerReturnCard.setInvalidDate(invalidDate);
            } catch (Exception e){
                throw new Exception("日期转换错误");
            }
        }
        if (customerReturnCard.getOrderDate() != null){
            try {
                Date orderDate = format.parse(format.format(customerReturnCard.getOrderDate()));
                customerReturnCard.setOrderDate(orderDate);
            } catch (Exception e){
                throw new Exception("日期转换错误");
            }
        }
        if (customerReturnCard.getCardSaleDate() != null){
            try {
                Date cardSaleDate = format.parse(format.format(customerReturnCard.getCardSaleDate()));
                customerReturnCard.setCardSaleDate(cardSaleDate);
            } catch (Exception e){
                throw new Exception("日期转换错误");
            }
        }
//        if (customerReturnCard.getStartTime() != null){
//            try {
//                Date startTime = format.parse(format.format(customerReturnCard.getStartTime()));
//                customerReturnCard.setStartTime(startTime);
//            } catch (Exception e){
//                throw new Exception("日期转换错误");
//            }
//        }
//        if (customerReturnCard.getEndTime() != null){
//            try {
//                Date endTime = format.parse(format.format(customerReturnCard.getEndTime()));
//                customerReturnCard.setEndTime(endTime);
//            } catch (Exception e){
//                throw new Exception("日期转换错误");
//            }
//        }

        List<CustomerReturnCard> customerReturnCardList = customerMapper.selectCustomerReturnCardByorderDate(customerReturnCard);
        if (customerReturnCardList != null && customerReturnCardList.size() > 0)
        {
            for (CustomerReturnCard returnCard : customerReturnCardList)
            {
                if (returnCard.getTime() != null)
                {
                    returnCard.setTmpTime(format.format(returnCard.getTime()));
                }

                if (returnCard.getDate() != null)
                {
                    returnCard.setTmpDate(format.format(returnCard.getDate()));
                }
                if (returnCard.getCardRecordId() != null)
                {
                    returnCard.setCardCode("");
                    returnCard.setTmpDate(null);
                }
            }
        }
        return customerReturnCardList;
    }

    @Override
    public List<CustomerCardGroupVO> getCustomerCardGroupList()
    {
        List<CustomerInfoDTO> lstCustomerInfo = customerMapper.getCustomerCardInfo(new CustomerResource());
        List<CardCRMAllDTO> lstCard = cardMapper.selectAllCard();
        List<CustomerCardGroupVO> lstCustomerCardGroup = new ArrayList<>();
        for (CardCRMAllDTO card: lstCard)
        {
            CustomerCardGroupVO customerCardGroupVO = new CustomerCardGroupVO();
            customerCardGroupVO.setCardId(card.getCardId());
            customerCardGroupVO.setCardName(card.getCardSectionName());
            for (CustomerInfoDTO customerInfo : lstCustomerInfo)
            {
                for (int i = 0; i < customerInfo.getLstCustomerCardInfo().size(); i++)
                {
                    for (int j = i; j < customerInfo.getLstCustomerCardInfo().size(); j++)
                    {
                        CustomerCardInfoDTO tmpCustomerCardInfo;
                        CustomerCardInfoDTO customerCardInfoDTOA = customerInfo.getLstCustomerCardInfo().get(i);
                        CustomerCardInfoDTO customerCardInfoDTOB = customerInfo.getLstCustomerCardInfo().get(j);
                        if (customerCardInfoDTOB.getCardLevel() > customerCardInfoDTOA.getCardLevel())
                        {
                            tmpCustomerCardInfo = customerCardInfoDTOA;
                            customerInfo.getLstCustomerCardInfo().set(i, customerCardInfoDTOB);
                            customerInfo.getLstCustomerCardInfo().set(j, tmpCustomerCardInfo);
                        }
                    }
                }
                if (card.getCardId().equals(customerInfo.getLstCustomerCardInfo().get(0).getCardId()))
                {
                    customerCardGroupVO.getLstCustomerInfo().add(customerInfo);
                }
            }
            lstCustomerCardGroup.add(customerCardGroupVO);
        }
        return lstCustomerCardGroup;
    }
    /**生成会员二维码*/
    @Override
    public String generateCustomerQrCode(String customerId) {
        return  DigestUtils.md5Hex(customerId);
    }



    @Override
    public Customer selectCustomerByContractPhoneOnes(String phone) {
        return customerMapper.selectCustomerByContractPhoneOnes(phone);
    }

    /**
     * 证件类型专用
     */
    public String Certificate(String certificateType) {
        switch (certificateType) {
            case "ID_CARD":
                certificateType = "身份证";
                break;
            case "MILITARY_ID":
                certificateType = "军人证";
                break;
            case "PASSPORT":
                certificateType = "护照";
                break;
            case "MTPFHKAMR":
                certificateType = "港澳居民来往内地通行证";
                break;
            case "MTPFTR":
                certificateType = "台湾居民来往大陆通行证";
                break;
            case "RPFHKMATR":
                certificateType = "港澳台居民居住证";
                break;
            case "PRICFF":
                certificateType = "外国人永久居留身份证";
                break;
            case "HKAMP":
                certificateType = "港澳通行证";
                break;
            case "ACCOUNT_BOOK":
                certificateType = "户口本";
                break;
            case "BIRTH_CERTIFICATE":
                certificateType = "出生证明";
                break;
            case "TAIWAN_PASS":
                certificateType = "台湾通行证";
                break;
        }
        return certificateType;
    }

    /**
     * 获取当前时间的后3个月时间并校验任意时间是否在该时间段内
     */
    public boolean dayTime(String eTime) {
        GregorianCalendar now = new GregorianCalendar();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        now.add(GregorianCalendar.MONTH, 3);
        String l = sdf.format(now.getTime());
        if (eTime.compareTo(l) <= 0) {
            return true;
        }
        return false;
    }

    /**
     * 获取当前会员所拥有的会员卡中等级最高的卡
     */
    public Card card(List<Card> cardList) {
        Card temporaryCard = null;
        Hashtable<String, Card> map = new Hashtable<>();
        for (Card card : cardList) {
            if (card.getCardSectionName().equals("体验会员")) {//体验会员
                map.put("1", card);
            } else if (card.getCardSectionName().equals("白银会员")) {//白银会员
                map.put("3", card);
            } else if (card.getCardSectionName().equals("黄金会员")) {//黄金会员
                map.put("4", card);
            } else if (card.getCardSectionName().equals("黑金会员·健康卡")) {//黑金会员·健康卡
                map.put("5", card);
            } else if (card.getCardSectionName().equals("黑金会员·出行卡")) {//黑金会员·出行卡
                map.put("6", card);
            }
        }

        for (String key : map.keySet()) {
            temporaryCard = map.get(key);
            break;
        }
        return temporaryCard;
    }
    /**
     * 检索三个月内未读的会员消息
     */
    @Override
    public List<CustomerMessage> selectCustomerMessage(CustomerMessage customerMessage) {
        Calendar cal = Calendar.getInstance();
        Date date=new Date();
        Date dBefore = new Date();//获取当前时间
        cal.setTime(date);
        cal.add(GregorianCalendar.MONTH, -3);//三个月前的时间
        dBefore = cal.getTime();//三个月前的时间
        customerMessage.setCreateTime(dBefore);
        return customerMapper.selectCustomerMessage(customerMessage);
    }
    /**
     * 检索三个月内未读的会员消息
     */
    @Override
    public List<CustomerMessage> selectAllCustomerMessage(CustomerMessage customerMessage) {
        Calendar cal = Calendar.getInstance();
        Date date=new Date();
        Date dBefore = new Date();//获取当前时间
        cal.setTime(date);
        cal.add(GregorianCalendar.MONTH, -3);//三个月前的时间
        dBefore = cal.getTime();//三个月前的时间
        customerMessage.setCreateTime(dBefore);
        return customerMapper.selectAllCustomerMessage(customerMessage);
    }
    /**
     * 新增会员消息
     */
    @Override
    public int addCustomerMessage(CustomerMessage customerMessage) {
        Date date=new Date();
        //新增时间
        customerMessage.setCreateTime(date);
        //设置未读
        customerMessage.setIsRead("unread");
        //业务线枚举

        //业务线订单号

        //会员id

        int i =customerMapper.addCustomerMessage(customerMessage);
        return i;
    }
    /**
     * 修改会员消息状态
     */
    @Override
    public int updateCustomerMessage(CustomerMessage customerMessage) {
        customerMessage.setIsRead("read");
        int i=customerMapper.updateCustomerMessage(customerMessage);
        return i;
    }

    /**
     * 根据会员信息查id
     * */
    @Override
    public CustomerIdVo customerId(CustomerIdVo customerIdVo) throws Exception {
        List<Card> cards = cardMapper.cardNum();
        //根据会员卡号获取会员id
        if (customerIdVo.getCustomerCard() != null && !customerIdVo.getCustomerCard().equals("")){
            CustomerCard customerCard = customerCardMapper.customerId(customerIdVo.getCustomerCard());
            if (customerCard != null){
                customerIdVo.setCustomerId(customerCard.getCustomerId());
            }
        }
        //根据会员其他信息获取会员卡号
        else {
            Customer customer = null;
            try {
                customer = customerMapper.selectCustomerIdByCustomerIdVo(customerIdVo);
            } catch (Exception e){
                throw new Exception("有重复数据，请完善您的查询条件，确保数据准确无误");
            }
            if (customer==null)
            {
                throw new Exception("没有查询到此会员信息！");
            }
            List<CustomerCard> customerCardList = customerCardMapper.CustomerCardList(customer.getCustomerId());
            if (customerCardList != null && customerCardList.size() > 0){
                int count = 0;
                int frequency = 0;
                for (CustomerCard customerCard : customerCardList) {
                    Card card = cardMapper.cardLevel(customerCard.getCardId());

                    if (cards.size() == 1){
                        customerCardList.sort((x, y) -> Double.compare(y.getCardLevel(), x.getCardLevel()));
                        customerIdVo.setCustomerCard(customerCardList.get(0).getCardCode());
                    }
                    else {
                        //会员每有一张黑金卡，frequency加1
                        if (card.getCardLevel() == cards.get(0).getCardLevel()){
                            frequency = frequency + 1;
                        }

                        //判断会员黑金卡数量是否大于1张
                        if (frequency > 1){
                            count = 1;
                        }
                        customerCard.setCardLevel(card.getCardLevel());
                    }
                }

                List<CustomerCard> customerCards = new ArrayList<>();
                //会员拥有不止一张黑金卡
                if (count == 1){
                    for (CustomerCard customerCard : customerCardList) {
                        if (customerCard.getCardLevel() == cards.get(0).getCardLevel()){
                            Long time = customerCard.getInvalidDate().getTime();
                            customerCard.setMillisecond(time);
                            customerCards.add(customerCard);
                        }
                    }
                    customerCards.sort((x, y) -> Double.compare(y.getMillisecond(), x.getMillisecond()));
                    customerIdVo.setCustomerCard(customerCards.get(0).getCardCode());
                }
                //会员只有一张或没有黑金卡,直接从大到小排序，取第一张会员卡信息的卡号
                else if (count == 0){
                    customerCardList.sort((x, y) -> Double.compare(y.getCardLevel(), x.getCardLevel()));
                    customerIdVo.setCustomerCard(customerCardList.get(0).getCardCode());
                }
            }
        }

        Customer customer = customerMapper.selectCustomerIdByCustomerIdVo(customerIdVo);
        customerIdVo.setCustomerId(customer.getCustomerId());
        customerIdVo.setCustomerName(customer.getCustomerName());
        customerIdVo.setCustomerPhone(customer.getContractPhoneOne());
        CustomerCard customerCard= customerCardMapper.selectCustomerCard(customerIdVo.getCustomerCard());

        if (customerCard != null && customerCard.getCardId() != null){
            Card card=cardMapper.selectCardByCardId(customerCard.getCardId());
            customerIdVo.setCustomerCardType(card.getCardSectionName());
            customerIdVo.setCardTypeId(card.getCardId());
            customerIdVo.setLevel(card.getCardLevel().toString());
        }

        customerIdVo.setLicenseNum(customer.getCustCertificateNo());

        List<PointRecord> pointRecordList = pointRecordMapper.integralStatistics(customerIdVo.getCustomerId());
        if (pointRecordList != null && pointRecordList.size() > 0){
            customerIdVo.setIntegral(pointRecordList.get(0).getAvailableValue().toString());
        }
        else {
            customerIdVo.setIntegral("0");
        }

        List<DepositBusiness> depositBusinessList = depositBusinessMapper.businessByCustomerId(customerIdVo.getCustomerId());
        if (depositBusinessList != null && depositBusinessList.size() > 0){
            customerIdVo.setGold(depositBusinessList.get(0).getAmount());
        }
        else {
            customerIdVo.setGold(new BigDecimal(0));
        }
        return customerIdVo;
    }

    /**
     * 查询待修改的会员详细信息
     * */
    @Override
    public CustomerDetailed customerDetailed(Long id) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        CustomerDetailed customerDetailed = new CustomerDetailed();
        Customer customer = customerMapper.selectCustomerById(id);
        if (customer != null){

            if (customer.getCreateTime() != null){
                customerDetailed.setTime(dateFormat.format(customer.getCreateTime()));
            }

            customerDetailed.setName(customer.getCustomerName());
            customerDetailed.setSex(customer.getCustomerSex());

            if (customer.getBirthday() != null){
                customerDetailed.setBirthday(format.format(customer.getBirthday()));
            }

            if (customer.getCustCertificateNo() != null){
                try {
                    int ageByIdCard = IDCardUtil.getAgeByIdCard(customer.getCustCertificateNo());
                    customerDetailed.setAge(String.valueOf(ageByIdCard));
                } catch (Exception e){
                    System.out.println("身份证号错误");
                }
                customerDetailed.setCertificateType(customer.getIdType());
                customerDetailed.setLicenseNum(customer.getCustCertificateNo());
            }
            customerDetailed.setContactRequest(customer.getContactRequest());
            customerDetailed.setPhone(customer.getContractPhoneOne());
            customerDetailed.setWeChatNum(customer.getWechatId());
            customerDetailed.setArea(customer.getCurrentCity());
            customerDetailed.setMailingAddress(customer.getMailingAddress());
            customerDetailed.setRemark(customer.getCustomerRemark());

            Date date = new Date();
            Date expired = null;
            try {
                date = format.parse(format.format(date));
                if (customer.getExpired() != null){
                    expired = format.parse(customer.getExpired());
                }

                if (expired != null){
                    if (date.compareTo(expired)  != -1){
                        customerDetailed.setValidityPeriod("false");
                    }
                    else {
                        customerDetailed.setValidityPeriod("true");
                    }
                }

            } catch (Exception e){
                System.out.println("日期转换错误");
            }
            customerDetailed.setProfession(customer.getProfession());
            customerDetailed.setJobTitle(customer.getJobTitle());
            customerDetailed.setCharacterTraits(customer.getCharacterTraits());
            customerDetailed.setCustomerPreferences(customer.getCustomerPreferences());
            customerDetailed.setNationality(customer.getNationality());
            customerDetailed.setMaritalStatus(customer.getMaritalStatus());
            customerDetailed.setChineseZodiac(customer.getChineseZodiac());
            customerDetailed.setConstellation(customer.getConstellation());
            customerDetailed.setLanguage(customer.getLanguage());
            customerDetailed.setCountryCitizenship(customer.getCountryCitizenship());
            customerDetailed.setHometown(customer.getHometown());
            customerDetailed.setProvince(customer.getCurrentCity());

            try {
                CustomerIdVo customerIdVo = new CustomerIdVo();
                customerIdVo.setCustomerId(id);
                customerIdVo = customerId(customerIdVo);

                if (customerIdVo != null){
                    customerDetailed.setMembershipLevel(Long.valueOf(customerIdVo.getLevel()));
                }
            } catch (Exception e){
                System.out.println("未查到会员等级信息");
            }
            customerDetailed.setBloodType(customer.getBloodType());
            customerDetailed.setModifyReason(customer.getModifyReason());

            List<CardDetails> cardDetailsList = new ArrayList<>();
            List<CustomerCard> customerCards = customerCardMapper.CustomerCardList(id);
            if (customerCards != null && customerCards.size() > 0){
                for (CustomerCard customerCard : customerCards) {
                    CardDetails cardDetails = new CardDetails();
                    cardDetails.setId(customerCard.getCustomerCardId().toString());

                    Card card = cardMapper.cardLevel(customerCard.getCardId());
                    if (card != null){
                        cardDetails.setCardType(card.getCardSectionName());
                    }

                    cardDetails.setCardNum(customerCard.getCardCode());
                    cardDetails.setName(customer.getCustomerName());

                    Employee employee = employeeMapper.backSelectEmployee(customerCard.getCarddmansId());
                    if (employee != null){
                        cardDetails.setCardSeller(employee.getEmployeeName());
                        cardDetails.setCardOpener(employee.getEmployeeName());
                    }
                    if (customerCard.getCreateTime() != null){
                        cardDetails.setDate(format.format(customerCard.getCreateTime()));
                    }
                    cardDetailsList.add(cardDetails);
                }
            }
            customerDetailed.setCardDetailsList(cardDetailsList);
            customerDetailed.setId(id);
        }
        return customerDetailed;
    }

    /**
     * 修改的会员详细信息
     * */
    @Override
    public int updateCustomerDetailed(CustomerDetailed customerDetailed) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Customer customer = new Customer();
        customer.setCustomerName(customerDetailed.getName());
        customer.setCustomerSex(customerDetailed.getSex());
        try {
            customer.setBirthday(format.parse(customerDetailed.getBirthday()));
        } catch (Exception e){
            throw new Exception("生日格式错误");
        }
        customer.setContactRequest(customerDetailed.getContactRequest());
        customer.setContractPhoneOne(customerDetailed.getPhone());
        customer.setIdType(customerDetailed.getCertificateType());
        customer.setCustCertificateNo(customerDetailed.getLicenseNum());
        customer.setWechatId(customerDetailed.getWeChatNum());
        customer.setMailingAddress(customerDetailed.getMailingAddress());
        customer.setCustomerRemark(customerDetailed.getRemark());
        customer.setProfession(customerDetailed.getProfession());
        customer.setJobTitle(customerDetailed.getJobTitle());
        customer.setCharacterTraits(customerDetailed.getCharacterTraits());
        customer.setCustomerPreferences(customerDetailed.getCustomerPreferences());
        customer.setNationality(customerDetailed.getNationality());
        customer.setMaritalStatus(customerDetailed.getMaritalStatus());
        customer.setChineseZodiac(customerDetailed.getChineseZodiac());
        customer.setConstellation(customerDetailed.getConstellation());
        customer.setLanguage(customerDetailed.getLanguage());
        customer.setCountryCitizenship(customerDetailed.getCountryCitizenship());
        customer.setHometown(customerDetailed.getHometown());
        customer.setCurrentCity(customerDetailed.getProvince());
        customer.setBloodType(customerDetailed.getBloodType());
        customer.setModifyReason(customerDetailed.getModifyReason());
        customer.setCustomerId(customerDetailed.getId());
        customer.setExpired(customerDetailed.getValidityPeriod());
        int i = customerMapper.updateCustomer(customer);
        return i;
    }

    /**
     * 会员 姓名/手机号查信息
     * */
    @Override
    public Customer nameAndPhone(String name, String phone) throws Exception {
        Customer customer = customerMapper.nameAndPhone(name, phone);
        if (customer==null)
        {
            return null;
        }
        CustomerIdVo customerIdVo = new CustomerIdVo();
        customerIdVo.setCustomerId(customer.getCustomerId());
        try {
            customerIdVo = customerId(customerIdVo);
        } catch (Exception e){
            throw new Exception(e.getMessage());
        }
        if (customerIdVo != null){
            customer.setCardType(customerIdVo.getCustomerCardType());
        }
        return customer;
    }

    @Override
    public Employee getVipEmployee(Long customerId)
    {
        EmployeeVipresource employeeVipresource = new EmployeeVipresource();
        employeeVipresource.setCustomerId(customerId);
        List<EmployeeVipresource> lstVipResource = employeeVipresourceMapper.selectEmployeeVipresourceList(employeeVipresource);
        if (CollectionUtil.isNotEmpty(lstVipResource))
        {
            Employee employee = employeeMapper.selectEmployeeById(lstVipResource.get(0).getEmployeeId());
            if (employee != null)
            {
                return employee;
            }
        }
        return null;
    }
}
